package com.videoweb.config.security.handle;

import com.alibaba.fastjson2.JSON;

import com.videoweb.constant.HttpStatus;
import com.videoweb.utils.AjaxResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 *
 * @author lmr
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
//        401
        int code = HttpStatus.UNAUTHORIZED;
        String msg = ("请求访问："+request.getRequestURI()+"认证失败，无法访问系统资源");

//                                                      这里设置的是返回消息的码 在响应数据里面
       renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }




    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string 待渲染的字符串
     */
    public static void renderString(HttpServletResponse response, String string)
    {
        try
        {
//            这里设置的是response的码
            response.setStatus(400);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }



}
